package com.xysq.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.rockcent.action.CallbackListener;
import com.rockcent.model.CustomerBO;
import com.rockcent.model.CustomerCouponBO;
import com.rockcent.model.TipsModel;
import com.xysq.activity.TipsActivity;
import com.xysq.adapter.TipsAdapter;
import com.xysq.lemon.R;
import com.xysq.util.ToastUtil;
import com.xysq.util.UseUtil;
import com.xysq.util.UserInfoKeeper;
import com.xysq.widget.LoadMoreListView;

import java.util.ArrayList;
import java.util.List;

public class TipsFragment extends BaseFragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    List<TipsModel> tipsModels;
    TipsAdapter tipsAdapter;
    int currentPage = CURRENT_PAGE;
    int pageSize = 40;

    com.xysq.widget.LoadMoreListView tipsList;
    TextView essenceTxt;
    TextView latestTxt;
    TextView insideSchoolTxt;
    TextView outsideSchoolTxt;
    int item;
    public static final int ESSENCE = 1;
    public static final int LATEST = 2;
    public static final int INSIDE_SCHOOL = 3;
    public static final int OUTSIDE_SCHOOL = 4;

    private OnFragmentInteractionListener mListener;

    // TODO: Rename and change types and number of parameters
    public static TipsFragment newInstance(String param1, String param2) {
        TipsFragment fragment = new TipsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public TipsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_tips, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_essence:
                item = ESSENCE;
                currentPage = 1;
                loadData();
                essenceTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
                latestTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                insideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                outsideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                break;
            case R.id.txt_latest:
                item = LATEST;
                currentPage = 1;
                loadData();
                essenceTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                latestTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
                insideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                outsideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                break;
            case R.id.txt_inside_school:
                item = INSIDE_SCHOOL;
                currentPage = 1;
                loadData();
                essenceTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                latestTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                insideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
                outsideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                break;
            case R.id.txt_outside_school:
                item = OUTSIDE_SCHOOL;
                currentPage = 1;
                loadData();
                essenceTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                latestTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                insideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.txt_white));
                outsideSchoolTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
                break;
        }
    }
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        loadData();
    }

    private void loadData() {
        switch (item) {
            case ESSENCE:
                //TODO
                loadEssence();
                break;
            case LATEST:
                loadLatest();
                break;
            case INSIDE_SCHOOL:
                loadInsideSchool();
                break;
            case OUTSIDE_SCHOOL:
                loadOutsideSchool();
                break;
        }
    }

    private void loadOutsideSchool() {
        appAction.getCustomer(UserInfoKeeper.readPhoneNumber(getActivity()), "", "", new CallbackListener<CustomerBO>() {
            @Override
            public void onSuccess(CustomerBO data) {
                final String mySchool = data.getSchoolName();
                appAction.listCustomerCouponsForPage("", "", currentPage, pageSize, new CallbackListener<List<CustomerCouponBO>>() {
                    @Override
                    public void onSuccess(List<CustomerCouponBO> data) {
                        if (data.size() != 0) {
                            if(currentPage == 1) {
                                tipsModels.clear();
                            }

                            for (int i = 0; i < data.size(); i++) {
                                if(!mySchool.equals(data.get(i).getExtend1())) {
                                    if(data.get(i).getIssueCount() == 0) {
                                        TipsModel tipsModel = new TipsModel();
                                        tipsModel.setContent(data.get(i).getIntroduce());
                                        tipsModel.setName(UseUtil.selectName(data.get(i).getNickName(), data.get(i).getCustomerName(), data.get(i).getPhone()));
                                        tipsModel.setSchool(data.get(i).getExtend1());
                                        tipsModel.setTimes(data.get(i).getSaleCount());
                                        tipsModel.setTitle(data.get(i).getName());
                                        tipsModel.setHeadUrl(data.get(i).getHeadUrl());
                                        tipsModel.setLogoUrl(data.get(i).getLogoUrl());
                                        tipsModel.setId(data.get(i).getId());
                                        tipsModel.setCustomerId(data.get(i).getCustomerId());
                                        tipsModels.add(tipsModel);
                                    }
                                }
                            }
                        }
                        tipsAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(String errorCode, String message) {
                        ToastUtil.showShort(getActivity(), "获取最新券失败");
                    }
                });
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    private void loadInsideSchool() {
        appAction.getCustomer(UserInfoKeeper.readPhoneNumber(getActivity()), "", "", new CallbackListener<CustomerBO>() {
            @Override
            public void onSuccess(CustomerBO data) {
                final String mySchool = data.getSchoolName();
                appAction.listCustomerCouponsForPage("", "", currentPage, pageSize, new CallbackListener<List<CustomerCouponBO>>() {
                    @Override
                    public void onSuccess(List<CustomerCouponBO> data) {
                        if (data.size() != 0) {
                            if(currentPage == 1) {
                                tipsModels.clear();
                            }
                            for (int i = 0; i < data.size(); i++) {
                                if (mySchool.equals(data.get(i).getExtend1())) {
                                    if (data.get(i).getIssueCount() == 0) {
                                        TipsModel tipsModel = new TipsModel();
                                        tipsModel.setContent(data.get(i).getIntroduce());
                                        tipsModel.setName(UseUtil.selectName(data.get(i).getNickName(), data.get(i).getCustomerName(), data.get(i).getPhone()));
                                        tipsModel.setSchool(data.get(i).getExtend1());
                                        tipsModel.setTimes(data.get(i).getSaleCount());
                                        tipsModel.setTitle(data.get(i).getName());
                                        tipsModel.setHeadUrl(data.get(i).getHeadUrl());
                                        tipsModel.setLogoUrl(data.get(i).getLogoUrl());
                                        tipsModel.setId(data.get(i).getId());
                                        tipsModel.setCustomerId(data.get(i).getCustomerId());
                                        tipsModels.add(tipsModel);
                                    }
                                }
                            }
                        }
                        tipsAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(String errorCode, String message) {
                        ToastUtil.showShort(getActivity(), "获取最新券失败");
                    }
                });
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    private void loadLatest() {
        appAction.listCustomerCouponsForPage("", null, currentPage, pageSize, new CallbackListener<List<CustomerCouponBO>>() {
            @Override
            public void onSuccess(List<CustomerCouponBO> data) {
                if (data.size() != 0) {
                    if(currentPage == 1) {
                        tipsModels.clear();
                    }
                    for (int i = 0; i < data.size(); i++) {
                        if(data.get(i).getIssueCount() == 0) {
                            TipsModel tipsModel = new TipsModel();
                            tipsModel.setContent(data.get(i).getIntroduce());
                            tipsModel.setName(UseUtil.selectName(data.get(i).getNickName(), data.get(i).getCustomerName(), data.get(i).getPhone()));
                            tipsModel.setSchool(data.get(i).getExtend1());
                            tipsModel.setTimes(data.get(i).getSaleCount());
                            tipsModel.setTitle(data.get(i).getName());
                            tipsModel.setHeadUrl(data.get(i).getHeadUrl());
                            tipsModel.setLogoUrl(data.get(i).getLogoUrl());
                            tipsModel.setId(data.get(i).getId());
                            tipsModel.setCustomerId(data.get(i).getCustomerId());
                            tipsModels.add(tipsModel);
                        }
                    }
                }
                tipsAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(getActivity(), "获取最新券失败");
            }
        });
    }

    private void loadEssence() {
        appAction.listCustomerCouponsForPage("", null, currentPage, pageSize, new CallbackListener<List<CustomerCouponBO>>() {
            @Override
            public void onSuccess(List<CustomerCouponBO> data) {
                if (data.size() != 0) {
                    if(currentPage == 1) {
                        tipsModels.clear();
                    }
                    for (int i = 0; i < data.size(); i++) {
                        if(data.get(i).getIssueCount() == 0) {
                            TipsModel tipsModel = new TipsModel();
                            tipsModel.setContent(data.get(i).getIntroduce());
                            tipsModel.setName(UseUtil.selectName(data.get(i).getNickName(), data.get(i).getCustomerName(), data.get(i).getPhone()));
                            tipsModel.setSchool(data.get(i).getExtend1());
                            tipsModel.setTimes(data.get(i).getSaleCount());
                            tipsModel.setTitle(data.get(i).getName());
                            tipsModel.setHeadUrl(data.get(i).getHeadUrl());
                            tipsModel.setLogoUrl(data.get(i).getLogoUrl());
                            tipsModel.setId(data.get(i).getId());
                            tipsModel.setCustomerId(data.get(i).getCustomerId());
                            tipsModels.add(tipsModel);
                        }
                    }
                    Log.e("tipsModel's size", tipsModels.size() + "");
                }
                tipsAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(getActivity(), "获取最新券失败");
            }
        });
//        appAction.listCustomerCoupons(UserInfoKeeper.readCustomerId(getActivity()), currentPage, new CallbackListener<List<CustomerCouponBO>>() {
//            @Override
//            public void onSuccess(List<CustomerCouponBO> data) {
//                if (data.size() != 0) {
//                    tipsModels.clear();
//                    for (int i = 0; i < data.size(); i++) {
//                        if(data.get(i).getIssueCount() == 0) {
//                            TipsModel tipsModel = new TipsModel();
//                            tipsModel.setContent(data.get(i).getIntroduce());
//                            tipsModel.setName(UseUtil.selectName(data.get(i).getNickName(), data.get(i).getCustomerName(), data.get(i).getPhone()));
//                            tipsModel.setSchool(data.get(i).getExtend1());
//                            tipsModel.setTimes(data.get(i).getSaleCount());
//                            tipsModel.setTitle(data.get(i).getName());
//                            tipsModel.setHeadUrl(data.get(i).getHeadUrl());
//                            tipsModel.setLogoUrl(data.get(i).getLogoUrl());
//                            tipsModel.setId(data.get(i).getId());
//                            tipsModel.setCustomerId(data.get(i).getCustomerId());
//                            tipsModels.add(tipsModel);
//                        }
//                    }
//                    tipsAdapter.notifyDataSetChanged();
//                }
//            }
//
//            @Override
//            public void onFailure(String errorCode, String message) {
//                ToastUtil.showShort(getActivity(), "获取精华券失败");
//            }
//        });
    }

    private void initView() {
        item = ESSENCE;
        tipsList = (com.xysq.widget.LoadMoreListView) getView().findViewById(R.id.list_tips);
        essenceTxt = (TextView) getView().findViewById(R.id.txt_essence);
        latestTxt = (TextView) getView().findViewById(R.id.txt_latest);
        insideSchoolTxt = (TextView) getView().findViewById(R.id.txt_inside_school);
        outsideSchoolTxt = (TextView) getView().findViewById(R.id.txt_outside_school);
        essenceTxt.setBackgroundColor(getResources().getColor(R.color.bg_blue));
        essenceTxt.setOnClickListener(this);
        latestTxt.setOnClickListener(this);
        insideSchoolTxt.setOnClickListener(this);
        outsideSchoolTxt.setOnClickListener(this);
        tipsModels = new ArrayList<>();
        tipsAdapter = new TipsAdapter(getActivity(), tipsModels);
        tipsList.setAdapter(tipsAdapter);
        tipsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TipsModel tipsModel = (TipsModel) tipsAdapter.getItem(position);
                Intent intent = new Intent(getActivity(), TipsActivity.class);
                intent.putExtra(TipsActivity.COUPONMODEL_ID, tipsModel.getId());
                intent.putExtra(TipsActivity.CUSTOMER_ID, tipsModel.getCustomerId());
                startActivity(intent);
            }
        });
        tipsList.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                new LoadDataTask().execute();
            }
        });
    }

    private class LoadDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            if (isCancelled()) {
                return null;
            }
            try {
                Thread.sleep(1000);
                currentPage++;
                loadData();
//                getComments();
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
//            evaluateAdapterVOnePointOne.notifyDataSetChanged();
            tipsList.onLoadMoreComplete();
            super.onPostExecute(result);
        }

        @Override
        protected void onCancelled() {
            tipsList.onLoadMoreComplete();
        }
    }
}
